<template>
  <div class="panel-account">
    <el-form
      :model="account"
      label-width="auto"
      size="large"
      :rules="accountRules"
      status-icon
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
// import { accountLoginRequest } from '@/service/login/login'
import { ElMessage } from 'element-plus'
import type { FormRules, ElForm } from 'element-plus'
import type { IAccount } from '@/types'
import useLoginStore from '@/store/login/login'
import { localCache } from '@/utils/cache'

const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

const accountRules: FormRules = {
  name: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{3,10}$/,
      message: '账号格式不正确',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{6,15}$/,
      message: '密码格式不正确',
      trigger: 'blur'
    }
  ]
}

// 子组件暴露出方法,这样父组件可以通过ref来捞取到子组件的方法
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(isRemPwd: boolean) {
  console.log('oansadasd', account)
  formRef?.value?.validate((valid) => {
    if (valid) {
      console.log('验证通过')
      // 1. 获取用户输入的账号和密码
      const name = account.name
      const password = account.password

      // 2. 进行网络请求 -- 该传法丢失响应式
      // accountLoginRequest({ name, password }).then((res) => {
      //   console.log('登录成功', res)
      // })
      // 通过store来进行网络请求存储
      loginStore.loginAccountAction({ name, password }).then((res) => {
        // 3. 判断是否需要记住密码
        if (isRemPwd) {
          localCache.setCache(CACHE_NAME, name)
          localCache.setCache(CACHE_PASSWORD, password)
        } else {
          localCache.removeCache(CACHE_NAME)
          localCache.removeCache(CACHE_PASSWORD)
        }
      })
    } else {
      console.log('验证失败')
      ElMessage.error('失败了')
    }
  })
}
defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.panel-account {
  color: red;
}
</style>
